#!/usr/bin/env python

"""
*****************************************************************
msg_import.py
This file is part of s60console project.

Released under GNU GPLv2.
See accompanying gpl-2.0.txt file
or visit http://www.gnu.org/licenses/gpl-2.0.txt

Author: Kashif Iftikhar (kashif [at] compulife.com.pk)

Description:
------------
module containing functions for importing messages

*****************************************************************
"""

import csv_parser
import message
import os
import sqlite3
import codecs
import re
import utility_code

DB_NAME = 'cellshell.db'

#9th September 2008 6:15:28 pm
date_time_re = re.compile('(\d+).. (\w+) (\d+) (\d+)\:(\d+)\:(\d+) (\w+)', re.S+re.U)


def convert_to_date(sdate):
    ret = sdate
    
    #[('9', 'September', '2008', '6', '15', '28', 'pm')]
    
    dMonths = {'January': '01',
               'February': '02',
               'March': '03',
               'April': '04',
               'May': '05',
               'June': '06',
               'July': '07',
               'August': '08',
               'September': '09',
               'October': '10',
               'November': '11',
               'December': '12'
               }
    matches = date_time_re.findall(sdate)
    if len(matches)>0:
        d = matches[0]
        ret = d[2].rjust(2, '0') + '-' + dMonths[d[1]] + '-' + d[0].rjust(2, '0')
        h = d[3]
        if 'pm' == d[6].lower():
            h = str(int(h)+12)
        
        ret += ' %s:%s:%s' % (h.rjust(2, '0'), d[4].rjust(2, '0'), d[5].rjust(2, '0'))
    
    return ret

    
def csv_to_msgs(csv_str, sep=','):
    "Converts given CSV string to message object(s)"
    msgs = []
    results = csv_parser.parse_csv(csv_str, sep)
    #print repr(results)
    for r in results:
        if len(r)>2:
            date_time = r[4] + ' ' + r[5]
            
            date_time = convert_to_date(date_time)
            
            M = message.Message(r[0], r[1], r[2], '', '', date_time, r[6], 'RECEIVED', r[7])
            #print M
            #print repr(M)
            msgs.append(M)
            
    return msgs

def msg_to_insert_sql(M):
    "Creates SQL insert statement from a message object"
    sql = """insert into messages(msg_type, sender_name, sender_phone, receiver_name, receiver_phone, msg_date,
    folder, msg_direction, message) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
    """ % (M.msg_type.replace("'", "''").replace('"', '""'),
           M.sender_name.replace("'", "''").replace('"', '""'),
           M.sender_phone.replace("'", "''").replace('"', '""'),
           M.receiver_name.replace("'", "''").replace('"', '""'),
           M.receiver_phone.replace("'", "''").replace('"', '""'),
           M.msg_date.replace("'", "''").replace('"', '""'),
           M.folder.replace("'", "''").replace('"', '""'),
           M.msg_direction.replace("'", "''").replace('"', '""'),
           M.message.replace("'", "''").replace('"', '""'))
    
    return sql

def import_from_file(filename, sep=','):
    "Imports messages into the DB from the given file."
    if os.path.exists(filename) and os.path.isfile(filename):
        f = codecs.open(filename, 'rb', encoding='utf-8')
        f = open(filename, 'r')
        data = f.read()
        f.close()
        
        # ignore first line.
        idx = data.find('\n') +1
        data = data[idx:]
        
        #data = unicode(data, 'utf8', 'ignore')
        #data = data.encode("utf-8", 'ignore')
        Ms = csv_to_msgs(data, sep)
        con = sqlite3.connect(DB_NAME)
        cur = con.cursor()
        
        for M in Ms:
            sql = msg_to_insert_sql(M)
            print sql
            cur.execute(sql)
        
        con.commit()
        con.close()
        
    else:
        print "Not a valid file"

def _tests():
    "Test cases for the module"
    import sput
    
    T = sput.tester()
    
    def _test_parse_command():
        "Unit tests for the csv_to_msgs function"
        csv_str = """"SMS";"Irum";"+923437158780";"";"10th June 2008";"12:36:35 am";"Archived 6001-6500";"Aur ap nay shubah parhana bhi, sara dimagh tu abhi kharch ho jaey ga aur ap thak jaen gay :-( "
"SMS";"Irum";"+923437158780";"";"10th June 2008";"12:33:15 am";"Archived 6001-6500";"Pakkay raqib ban gaey hain yeh tu"
"SMS";"Irum";"+923437158780";"";"10th June 2008";"12:31:07 am";"Archived 6001-6500";"Janu army walay hain abhi bhi ?"
"SMS";"Imran Afzal";"+923345423826";"";"9th June 2008";"11:50:22 pm";"Archived 6001-6500";""laa ilaaha illallaho,muhammad ur rsulullah"" yeh msg 9 logo ko send kro aj rat good news mily gi ye madina se shuru hua hai is ko nzr andaz mat krna "
"SMS";"Irum";"+923437158780";"";"9th June 2008";"11:25:55 pm";"Archived 6001-6500";"Kashif janu ap nay khana khaya?"
"""
        valid_r = {'message': ' This is just a simple msg', 'cmd': 'SENDSMS', 'contact': '+92343545454'}
        T.add_test("****** csv_to_msgs test: %s" % csv_str, csv_to_msgs, valid_r, csv_str, ';')
        
        Ms = csv_to_msgs(csv_str, ';')
        for M in Ms:
            print msg_to_insert_sql(M)
    
    
    _test_parse_command()
    
    T.run_all_tests()

if __name__ == '__main__':
    import sys
    if len(sys.argv)>1 and 'run_tests'==sys.argv[1]:
        _tests()
    
    if len(sys.argv)>1:
        for f in sys.argv[1:]:
            import_from_file(f, ';')